﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Input;
using Socium.Domain.Collections;
using Socium.Domain.Tests.Sociometric;
using Socium.Presentation;

namespace Socium.Tests.Procedures {
	class ProceduresIndexViewModel : PageViewModel {
		readonly ICollection<Procedure> _procedures;
		readonly IFormViewService _form_view_service;

		public ProceduresIndexViewModel(string display_name, ICollection<Procedure> procedures, IFormViewService form_view_service) : base(display_name) {
			_procedures = procedures;
			_form_view_service = form_view_service;

			_items.CollectionChanged += ItemsCollectionChanged;
			_items.AddRange(procedures.MapLazy(procedure => new ProcedureLineItem(procedure)));

			NewItemCommand = new Command(OnNewItem);

			DisplayName = "Procedures";
		}

		void ItemsCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) {
			if (e.NewItems != null) {
				foreach (ProcedureLineItem new_item in e.NewItems) {
					new_item.Edit += OnEditItem;
					new_item.Delete += OnDeleteItem;
				}
			}

			if (e.OldItems != null) {
				foreach (ProcedureLineItem old_item in e.OldItems) {
					old_item.Edit -= OnEditItem;
					old_item.Delete -= OnDeleteItem;
				}
			}
		}

		#region Items

		readonly ObservableCollection<ProcedureLineItem> _items = new ObservableCollection<ProcedureLineItem>();

		public ICollection<ProcedureLineItem> Items {
			get { return _items; }
		}

		#endregion

		#region New item

		public ICommand NewItemCommand { get; private set; }

		void OnNewItem() {
			var view_model = new ProcedureViewModel();
			
			view_model.ModelCreated += procedure => {
				_procedures.Add(procedure); 
				_items.Add(new ProcedureLineItem(procedure));
			};

			//view_model.ModelUpdated += procedure => _items.Any(item => item.Update(procedure));

			_form_view_service.Show(view_model);
		}

		#endregion

		#region Edit item

		void OnEditItem(ProcedureLineItem line_item, Procedure procedure) {
			var view_model = new ProcedureViewModel(procedure);
			view_model.ModelUpdated += line_item.Update;
			_form_view_service.Show(view_model);
		}

		#endregion

		#region Delete item

		void OnDeleteItem(ProcedureLineItem line_item, Procedure procedure) {
			_procedures.Remove(procedure);
			_items.Remove(line_item);
		}

		#endregion

	}
}
